import axios from 'axios';
import storage from "@/global/storage";
import { Message } from "element-ui";

axios.defaults.withCredentials = true;
axios.defaults.timeout = 20000;
axios.defaults.baseURL = '/admin'

/**请求拦截 */
axios.interceptors.request.use(
    config => {
        if (config.method == 'get' || config.method == 'delete') {
            const newParams = config.params === undefined || config.params === null ? null : config.params;

            if (newParams) {
                newParams.keywor = encodeURI(newParams.keywor);
                const params = JSON.stringify(newParams);
                config.headers.params = params;
            }
        }
        const TOKEN = storage.get('token');

        if (TOKEN) {
            config.headers.Authorization = `Bearer ${TOKEN}`;
        }

        return config;
    },
    error => Promise.reject(error)
);

// 全局错误处理
const handleErrorRequest = error => {
    const { response } = error;
    const status = response ? response.status : 408;
    if (response) {
        const { data } = response;
        const { errors } = data;
        const message = data.message || "服务器发送错误，请稍后再试";
        if (status === 401) {
            Message.error("没有登录")
        } else if (status === 419) {
            Message.error("页面过期");

        } else if (status === 422 || status === 423 || status === 429) {
            Object.keys(errors).forEach(errorKey => {
                const errorValue = errors[errorKey].join("\n");
                Message.error(errorValue);
            });
        } else {
            Message.error(message);
        }
    } else {
        Message.error("网络超时");
    }
};

/**响应拦截 */
axios.interceptors.response.use(
    res => {
        switch (true) {
            case res.data.code && res.data.code != 200:
                Message.error(res.data.msg)
                return Promise.reject(res.data);
            case !res.data.code:
                return res.data;
            default:
                return res.data;
        }
    },
    error => {
        handleErrorRequest(error);
        return Promise.reject(error)
    }
)


/* [请求库]
** @params url         { string }   @default => '' [接口地址]
** @params data/params { object }   @default => {} [发送数据]
** @params config      { object }   配置
*/

export default {
    post: function (url = '', data = {}, config) {
        return axios.post(url, data, config);
    },

    put: function (url = '', data = {}, config) {
        return axios.put(url, data, config);
    },

    get: function (url, data = {}, config) {
        let OPTIONS = Object.assign(data, config);
        return axios.get(url, OPTIONS)
    },

    delete: function (url = '', data = {}, config) {
        let OPTIONS = Object.assign(data, config);
        return axios.delete(url, OPTIONS)
    }
}